// pages/my/my.js
const app = getApp()
Page({
  data: {
    userInfo: {},
    assets: {},
    counts: {},
    isLogin: false,
    isLogoutShow: false,
    isLoginShow: false
  },
  onShow() {
    this.onRefreshPage()
  },
  // 页面刷新
  onRefreshPage() {
    this.getUserInfo()
    this.getUserAssets()
    this.getOrderCounts()
    this.setData({isLogoutShow: false, isLoginShow: false})
  },
  // 未登录弹框
  loginCancel() {
    this.setData({isLoginShow: false})
  },
  loginConfirm() {
    this.setData({isLoginShow: false})
    wx.navigateTo({
      url: '../../user_pkg/pages/login/login'
    })
  },
  // 登录
  login() {
    wx.navigateTo({
      url: '../../user_pkg/pages/login/login',
    })
  },
  // 退出登录
  logoutModal() {
    this.setData({isLogoutShow: true})
  },
  logout() {
    wx.http.token = ''
    getApp().setToken('token', '')
    this.setData({isLogoutShow: false, isLogin: false})
    this.onRefreshPage()
  },
  logoutCancel() {
    this.setData({isLogoutShow: false})
  },
  // 获取用户信息
  async getUserInfo() {
    const res = await wx.http.get('/user/info')
    if(res.data.status !== 401) {
      const userInfo = res.data.data.userInfo
      const userId = res.data.data.userInfo.user_id
      if(userId) {
        getApp().setUserLoginStatus(userId)
        this.setData({isLogin: true})
      }
      this.setData({userInfo})
    } else {
      this.setData({userInfo: {}})
      getApp().setUserLoginStatus('')
    }
  },
  // 获取余额、积分、优惠券
  async getUserAssets() {
    const res = await wx.http.get('/user/assets')
    if(res.data.status !== 401) {
      const assets = res.data.data.assets
      this.setData({assets})
    } else {
      this.setData({assets: {}})
    }
  },
  // 获取商品状态数量
  async getOrderCounts() {
    const res = await wx.http.get('/order/todoCounts')
    if(res.data.status !== 401) {
      const counts = res.data.data.counts
      this.setData({counts})
    } else {
      this.setData({counts: {}})
    }
  },
  // 跳转钱包页面
  toWallet() {
    if(!this.data.isLogin) {
      this.setData({isLoginShow: true})
    } else {
      wx.navigateTo({
        url: '../../user_pkg/pages/wallet/wallet'
      })
    }
  },
  // 跳转收货地址页面
  toAddress() {
    if(!this.data.isLogin) {
      this.setData({isLoginShow: true})
    } else {
      wx.navigateTo({
        url: '../../user_pkg/pages/address/address'
      })
    }
  },
  // 跳转订单页
  toOrder(ev) {
    const dataType = ev.mark.dataType
    wx.navigateTo({
      url: `../../order_pkg/pages/order/order?dataType=${dataType}`
    })
  }
})